import requests
from PIL import Image
from io import BytesIO
import ddddocr
import json # 导入json库，方便格式化打印结果

def run_recognition_test():
    """
    一个独立的测试函数，用于下载指定的滑块和背景图，并使用ddddocr进行识别。
    """
    # --- 1. 请在这里填入你要测试的两个图片的URL ---
    # 背景图 URL (从您之前的报错信息中获取)
    background_url = "https://cdn.wenanzhe.com/img/a.png"
    # 滑块图片 URL (请务必替换成您自己的滑块图片URL)
    target_url = "https://cdn.wenanzhe.com/img/b.png"

    print("测试开始...")
    print(f"背景图 URL: {background_url}")
    print(f"滑块图 URL: {target_url}")

    # --- 2. 配置网络代理 ---
    # !!! 重要: 请根据你自己的代理软件修改这里的地址和端口 !!!
    proxies = {
       'http': 'http://127.0.0.1:7890',
       'https': 'http://127.0.0.1:7890',
    }

    try:
        # --- 3. 下载图片 ---
        print("\n正在下载图片 (通过代理)...")
        background_resp = requests.get(background_url, timeout=15, proxies=proxies)
        target_resp = requests.get(target_url, timeout=15, proxies=proxies)
        background_resp.raise_for_status()
        target_resp.raise_for_status()
        print("图片下载成功。")

        # --- 4. 预处理图片 ---
        print("正在处理图片...")
        background_img = Image.open(BytesIO(background_resp.content)).convert("RGB")
        target_img = Image.open(BytesIO(target_resp.content)).convert("RGBA")

        background_img = background_img.resize((340, 212), Image.Resampling.LANCZOS)
        target_img = target_img.resize((68, 68), Image.Resampling.LANCZOS)

        with BytesIO() as target_buffer:
            target_img.save(target_buffer, format="PNG")
            target_bytes = target_buffer.getvalue()

        with BytesIO() as background_buffer:
            background_img.save(background_buffer, format="JPEG")
            background_bytes = background_buffer.getvalue()
        print("图片处理完成。")

        # --- 5. 调用 ddddocr 进行识别 ---
        print("正在调用 ddddocr 进行识别...")
        det = ddddocr.DdddOcr(det=False, ocr=False, show_ad=False)
        result = det.slide_match(target_bytes, background_bytes, simple_target=True)
        print("=========美化前的结果========")
        print(result)
        # --- 6. 打印最终结果 ---
        print("\n" + "="*20 + " 识别结果 " + "="*20)
        # 使用json.dumps美化输出，方便查看
        print("=========美化后的结果========")
        print(json.dumps(result, indent=2))
        print("="*50)

    except requests.exceptions.RequestException as e:
        print(f"\n[错误] 图片下载失败: {e}")
    except Image.UnidentifiedImageError:
        print("\n[错误] 无法识别图片格式，请确保URL是有效的图片。")
    except Exception as e:
        print(f"\n[错误] 发生未知异常: {e}")

# --- 主程序入口 ---
if __name__ == "__main__":
    run_recognition_test()